package com.bjx.flow.approve.user.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.bjx.api.system.domain.query.UserQuery;
import com.bjx.api.system.domain.vo.UserVO;
import com.bjx.api.system.service.RemoteUserService;
import com.bjx.common.core.constant.FrameConst;
import com.bjx.common.core.domain.R;
import com.bjx.common.core.exception.BJXException;
import com.bjx.flow.approve.user.ApprovalUserDispose;
import com.bjx.api.system.domain.bo.ExecuteBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc: 解析用户
 * @author: liushuai
 * @date: 2022/11/17 22:07
 */
@Service("userDisposeHandler")
@Slf4j
public class UserDisposeHandler extends ApprovalUserDispose {
    @Resource
    private RemoteUserService remoteUserService;
    @Override
    public void dispose(JSONObject jsonObject,List<UserVO> users) {
        JSONArray jsonArray = jsonObject.getJSONArray("user");
        if(CollectionUtil.isNotEmpty(jsonArray)){
            List<ExecuteBO> executes = Convert.toList(ExecuteBO.class,jsonArray);
            List<Long> ids = executes.stream().map(ExecuteBO::getValue).map(Long::valueOf).collect(Collectors.toList());
            UserQuery userQuery = UserQuery.builder()
                    .userIds(ids)
                    .build();
            R<List<UserVO>> r = remoteUserService.listUserVOByIds(userQuery);
            if(r.getCode() == FrameConst.FAIL.intValue()){
                log.error("调用远程用户接口失败:{}",r.getMsg());
                throw new BJXException("调用远程用户接口失败");
            }
            List<UserVO> data = r.getData();
            users.addAll(data);
        }
        this.executeNext(jsonObject,users);
    }
}
